<?php


namespace App\Model;


use App\Util\Ip2Region;
use App\Util\SystemErr;
use EasySwoole\EasySwoole\Task\TaskManager;
use EasySwoole\Http\Request;
use EasySwoole\Mysqli\QueryBuilder;
use EasySwoole\ORM\AbstractModel;

class AdmLoginLog extends AbstractModel
{
    protected $autoTimeStamp = true;
    protected $updateTime = false;
    protected $tableName  = 'adm_login_log';


    public static function rlog( Request $req, int $user_id){
        $ip = $req->getHeaderLine('x-real-ip');
        $ua = $req->getHeaderLine('user-agent');
        TaskManager::getInstance()->async(function () use ($ip,$ua, $user_id){
            try{
                $ip_city_data = Ip2Region::getInstance()->memorySearch($ip);
                $data = [
                    'ip'        => $ip,
                    'user_agent'    => $ua,
                    'user_id'   => $user_id,
                ];
                self::create(array_merge($data, $ip_city_data))->save();
            } catch ( \Throwable $e){
              SystemErr::write($e,'[Model.AdmLoginLog.rlog]');
            }
        });
    }


    public function usr(){
        return $this->hasOne(Adm::class,function ( QueryBuilder $Q){
            return $Q->fields('id,name,phone,status');
        },'user_id','id');
    }


    protected function getCreateTimeAttr( $v ){
        return date('Y-m-d H:i:s',$v);
    }
}